package com.zs.zcerp.entrance.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zs.zcerp.entrance.entity.*;
import com.zs.zcerp.entrance.service.IEntranceAccessService;
import com.zs.zcerp.util.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class EntranceAccessServiceImpl implements IEntranceAccessService {

    private final static Logger logger = LoggerFactory.getLogger(EntranceAccessServiceImpl.class);

    final static SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    final static SimpleDateFormat df1= new SimpleDateFormat("yyyy-MM-dd");



    @Autowired
    private EntranceAccessConfig eac;

    @Override
    public String CreateDept(DpDept dpDept) {
        return HttpUtils.doPostJson(createURL(eac.getCreateDeptURI()), JSON.toJSONString(dpDept));
    }

    @Override
    public String UpdateDept(DpDept dpDept) {
        return HttpUtils.doPostJson(createURL(eac.getUpdateDeptURI()), JSON.toJSONString(dpDept));
    }

    @Override
    public String DeleteDept(DpDept dpDept) {
        return HttpUtils.doPostJson(createURL(eac.getDeleteDeptURI()), JSON.toJSONString(dpDept));
    }

    @Override
    public String GetDeptSub(DpDept dpDept) {
        return HttpUtils.doPostJson(createURL(eac.getGetDeptSubURI()), JSON.toJSONString(dpDept));
    }

    @Override
    public String CreatePost(Post post) {
        return HttpUtils.doPostJson(createURL(eac.getCreatePostURI()), JSON.toJSONString(post));
    }

    @Override
    public String UpdatePost(Post post) {
        return HttpUtils.doPostJson(createURL(eac.getUpdatePostURI()), JSON.toJSONString(post));
    }

    @Override
    public String DeletePost(Post post) {
        return HttpUtils.doPostJson(createURL(eac.getDeletePostURI()), JSON.toJSONString(post));
    }

    @Override
    public String GetPost() {
        return HttpUtils.doPost(createURL(eac.getGetPostURI()), null);
    }

    @Override
    public String CreateEmp(EpMain epMain) {
        // 转换性别
        if ("F".equals(epMain.getGender())) {
            epMain.setGender("0");
        } else if ("M".equals(epMain.getGender())) {
            epMain.setGender("1");
        }
        // 转换状态
        String empState = epMain.getEmpState();
        if ("1".equals(empState) || "3".equals(empState) || "5".equals(empState)) {
            epMain.setEmpState("1");
        } else {
            epMain.setEmpState("3");
        }
        return HttpUtils.doPostJson(createURL(eac.getCreateEmpURI()), JSON.toJSONString(epMain));
    }

    @Override
    public String UpdateEmp(EpMain epMain) {
        // 转换性别
        if ("F".equals(epMain.getGender())) {
            epMain.setGender("0");
        } else if ("M".equals(epMain.getGender())) {
            epMain.setGender("1");
        }
        // 转换状态
        String empState = epMain.getEmpState();
        if ("1".equals(empState) || "3".equals(empState) || "5".equals(empState)) {
            epMain.setEmpState("1");
        } else {
            epMain.setEmpState("3");
        }
        return HttpUtils.doPostJson(createURL(eac.getUpdateEmpURI()), JSON.toJSONString(epMain));
    }

    @Override
    public String DeleteEmp(EpMain epMain) {
        return HttpUtils.doPostJson(createURL(eac.getDeleteEmpURI()), JSON.toJSONString(epMain));
    }

    @Override
    public String GetEmp(EpMain epMain) {
        return HttpUtils.doPostJson(createURL(eac.getGetEmpURI()), JSON.toJSONString(epMain));
    }

    @Override
    public String GetDeptEmp(DeptEmp deptEmp) {
        return HttpUtils.doPostJson(createURL(eac.getGetDeptEmpURI()), JSON.toJSONString(deptEmp));
    }

    @Override
    public void CreateOrUpdateSyorg(Syorg syorg) {
        DpDept dpDept = new DpDept();
        dpDept.setDeptId(String.valueOf(syorg.getOrgId()));
        dpDept.setName(syorg.getShortnmT());
        dpDept.setParentId("0");
        // 创建公司
        String resCreate = CreateDept(dpDept);
        JSONObject createJson = JSON.parseObject(resCreate);
        if (createJson.containsKey("errcode") && createJson.getIntValue("errcode") == 0) {
            logger.info(df.format(new Date()) + ", 创建新公司:" + JSON.toJSONString(dpDept));
        } else {
            // 如果创建公司失败, 有可能公司已存在, 尝试更新公司
            String resUpdate = UpdateDept(dpDept);
            JSONObject updateJson = JSON.parseObject(resUpdate);
            if (updateJson.containsKey("errcode") && updateJson.getIntValue("errcode") == 0) {
                logger.info(df.format(new Date()) + ", 更新公司:" + JSON.toJSONString(dpDept));
            }
        }
    }

    @Override
    public void CreateOrUpdateDpDept(DpDept dpDept) throws Exception{
        dpDept.setDeptId(dpDept.getOrgId() + dpDept.getDeptNo());
        if ("810001".equals(dpDept.getDeptId())) {
            dpDept.setName("站佳事业部");
        }
        if ("640020".equals(dpDept.getDeptId())) {
            dpDept.setName("null");
        }
        String parentId = dpDept.getHighDept() == null? String.valueOf(dpDept.getOrgId()) : (dpDept.getOrgId() + dpDept.getHighDept());
        dpDept.setParentId(parentId);
        // 创建部门
        String resCreate = CreateDept(dpDept);
        JSONObject createJson = JSON.parseObject(resCreate);
        if (createJson.containsKey("errcode") && createJson.getIntValue("errcode") == 0) {
            logger.info(df.format(new Date()) + ", 创建新部门:" + JSON.toJSONString(dpDept));
        } else if (createJson.containsKey("errmsg")){
            // 检查是否父部门还未插入
            if ("父部门ID不存在".equals(createJson.getString("errmsg"))) {
                throw new Exception();
            } else if ("部门ID已存在".equals(createJson.getString("errmsg"))){
                // 尝试更新部门
                String resUpdate = UpdateDept(dpDept);
                JSONObject updateJson = JSON.parseObject(resUpdate);
                if (updateJson.containsKey("errcode") && updateJson.getIntValue("errcode") == 0) {
                    logger.info(df.format(new Date()) + ", 更新部门:" + JSON.toJSONString(dpDept));
                }
            } else if ("同一级下存在相同部门名称".equals(createJson.getString("errmsg"))){
                JSONObject jsonObject = renameDept(dpDept);
                if (jsonObject.containsKey("errcode") && jsonObject.getIntValue("errcode") == 0) {
                    logger.info(df.format(new Date()) + ", 创建重命名新部门:" + JSON.toJSONString(dpDept));
                }
            }
        }
    }

    @Override
    public void CreateOrUpdatePost(Post post) {
        // 创建职位
        String resCreate = CreatePost(post);
        JSONObject createJson = JSON.parseObject(resCreate);
        if (createJson.containsKey("errcode") && createJson.getIntValue("errcode") == 0) {
            logger.info(df.format(new Date()) + ", 创建新职位:" + JSON.toJSONString(post));
        } else {
            // 如果创建职位失败, 有可能职位已存在, 尝试更新职位
            String resUpdate = UpdatePost(post);
            JSONObject updateJson = JSON.parseObject(resUpdate);
            if (updateJson.containsKey("errcode") && updateJson.getIntValue("errcode") == 0) {
                logger.info(df.format(new Date()) + ", 更新职位:" + JSON.toJSONString(post));
            }
        }
    }

    @Override
    public void CreateOrUpdateEmp(EpMain epMain) {
        epMain.setDeptId(epMain.getOrgId() + epMain.getDeptNo());
        // 创建员工
        String resCreate = CreateEmp(epMain);
        JSONObject createJson = JSON.parseObject(resCreate);
        if (createJson.containsKey("errcode") && createJson.getIntValue("errcode") == 0) {
            logger.info(df.format(new Date()) + ", 创建新员工:" + epMain.getEmpCode() + "::" + epMain.getName());
        } else {
            // 如果创建员工失败, 有可能员工已存在, 尝试更新职位
            String resUpdate = UpdateEmp(epMain);
            JSONObject updateJson = JSON.parseObject(resUpdate);
            if (updateJson.containsKey("errcode") && updateJson.getIntValue("errcode") == 0) {
                logger.info(df.format(new Date()) + ", 更新员工:" + epMain.getEmpId() + "::" + epMain.getName());
            }
        }
    }

    @Override
    public String UpdateAttendancePlan(Attendance attendance) {
        return HttpUtils.doPostJson(createURL(eac.getUpdateAttendancePlan()), JSON.toJSONString(attendance));
    }

    @Override
    public String DeleteAttendancePlan(Attendance attendance) {
        return HttpUtils.doPostJson(createURL(eac.getDeleteAttendancePlan()), JSON.toJSONString(attendance));
    }

    @Override
    public String GetAskLeaveRecord(Integer status, Integer size, Integer cursor, Date startTime, Date endTime) {
        JSONObject data = new JSONObject();
        data.put("status", status);
        data.put("starttime", df1.format(startTime));
        data.put("endtime", df1.format(endTime));
        data.put("size", size);
        data.put("cursor", cursor);
        return HttpUtils.doPostJson(createURL(eac.getGetAskLeaveRecord()), data.toJSONString());
    }

    @Override
    public String GetAskLeaveRecordByApplyTime(Integer status, Date startTime, Date endTime, Integer size, Integer cursor) {
        JSONObject data = new JSONObject();
        data.put("status", status);
        data.put("starttime", df1.format(startTime));
        data.put("endtime", df1.format(endTime));
        data.put("size", size);
        data.put("cursor", cursor);
        return HttpUtils.doPostJson(createURL(eac.getGetAskLeaveRecordByApplyTime()), data.toJSONString());
    }

    /**
     * 拼接URL
     * @param uri
     * @return
     */
    private String createURL(String uri) {
        return "http://" + eac.getIp() + ":" + eac.getPort() + "/"  + uri + "?access_token=" + eac.getACCESS_TOKEN();
    }

    /**
     * 重命名部门
     * @param dpDept
     * @return
     */
    private JSONObject renameDept(DpDept dpDept) {
        // 重命名部门
        int version = 2;
        JSONObject createJson = new JSONObject();
        do {
            dpDept.setName(dpDept.getName() + version++);
            createJson = JSON.parseObject(CreateDept(dpDept));
        } while ("同一级下存在相同部门名称".equals(createJson.getString("errmsg")));
        return createJson;
    }
}
